package cn.ddiancan.xddcloud.common.interceptor;

import cn.ddiancan.xddcloud.common.context.CloudRequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.HttpRequestWrapper;
import org.springframework.util.MultiValueMap;

import java.io.IOException;

/**
 * 外部调用，从外部请求过来的请求头拦截器
 *
 * @author Amos
 */
@Slf4j
public class InComingRequestInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {
        // 整合外部请求头
        try {
            if (CloudRequestContext.isCurrentThreadInitialized()) {
                MultiValueMap<String, String> inComing = CloudRequestContext.getContextForCurrentThread().getInComing();
                HttpRequest requestWrapper = new HttpRequestWrapper(request);
                requestWrapper.getHeaders().addAll(inComing);
                return execution.execute(requestWrapper, body);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return execution.execute(request, body);
    }
}
